﻿#ifndef CDBCONNECTOR_H_
#define CDBCONNECTOR_H_

#include <iostream>
#include <QSqlQuery>

#include "CommonType.h"

namespace zl {

/// \brief 数据库连接模块
class CDBConnector
{
public:	
    /// \brief 错误码
    enum EDBError
    {
        EDBError_Success = 0x00,
		EDBError_DatabaseError,
		EDBError_ConnectFailed,
		EDBError_InitDatabaseFailed,
		EDBError_ExecQueryFailed,
        EDBError_Undefined = 0xFF
	};

    /// \brief 数据库类型
    enum EDBType
    {
		EDBType_MYSQL			= 0x01,
		EDBType_SQLITE3			= 0x02,
		EDBType_SQLSERVER		= 0x03,
		EDBType_ORCAL			= 0x04
	};

    /// \brief 数据库配置信息
    struct DBConfig
    {
        int32_t port;
        int32_t type;
        std::string addr;
        std::string user;
        std::string pwd;
        std::string name;
    };

    /// \brief 单例接口
	static CDBConnector* Instance();
	static void Release();

    int32_t Initialize(const DBConfig& conf);
    int32_t Uninitialize();
	QSqlQuery CreateQuery();
	int32_t ExecQuery(QSqlQuery& query);
	int32_t ExecBatchQuery(QSqlQuery& query);
    int32_t ExecSql(const QString& sql);

protected:
	int32_t init_database();
    int32_t init_database_mysql();
    int32_t init_database_sqlite3();
	void begin_transaction();
	void query_commit();
	void query_rollback();
	void reconnect_database();

private:
	explicit CDBConnector() = default;
	~CDBConnector() = default;

	static CDBConnector*	instance_;
	QSqlDatabase			db_;
    DBConfig                config_;
};

}

#endif // CDBCONNECTOR_H_
